<route>
{
  "layout": "default",
  "style": {
    "navigationBarTitleText": "社区",
    "navigationStyle": "custom"
  }
}
</route>

<template>
  <view class="page-container">
    <view class="header-wrapper" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="header">
        <view class="header-search">
          <view class="search-box">
            <text class="search-icon">🔍</text>
            <input class="search-input" disabled placeholder="探索" placeholder-class="search-placeholder" />
          </view>
          <view class="checkin-btn">
            <text>签到</text>
          </view>
        </view>
        <scroll-view scroll-x class="tab-bar" show-scrollbar="false">
          <view class="tab-list">
            <view v-for="tab in tabList" :key="tab" class="tab-item" :class="{ active: tab === activeTab }" @tap="handleTabChange(tab)">
              <text>{{ tab }}</text>
              <view v-if="tab === activeTab" class="tab-active-line"></view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <view class="page-body">
      <scroll-view
        scroll-y
        id="community-scroll"
        class="content-scroll"
        :style="{ height: scrollViewHeight + 'px' }"
        :scroll-with-animation="true"
        refresher-enabled
        :refresher-triggered="refresherTriggered"
        refresher-default-style="none"
        refresher-background="#fff"
        :refresher-threshold="100"
        @refresherrefresh="handleRefresh"
        @scrolltolower="handleScrollToLower"
        :lower-threshold="50"
      >
        <view slot="refresher" class="custom-refresher">
          <view class="custom-refresher-spinner" :class="{ active: refresherTriggered }"></view>
          <text class="custom-refresher-text">
            {{ refresherTriggered ? '刷新中...' : '下拉刷新' }}
          </text>
        </view>
        <view class="scroll-inner">
          <view class="hot-section">
            <view class="section-title">
              <text>热榜</text>
            </view>
            <view class="hot-list">
              <view v-for="item in hotList" :key="item.rank" class="hot-item">
                <view class="hot-left">
                  <view class="hot-rank" :class="{ top: item.rank <= 3 }">
                    {{ item.rank }}
                  </view>
                  <view class="hot-info">
                    <text class="hot-title">{{ item.title }}</text>
                    <text class="hot-meta">{{ item.heat }} 热度</text>
                  </view>
                </view>
                <text class="hot-tag">{{ item.tag }}</text>
              </view>
            </view>
          </view>

          <view class="post-section">
            <view v-for="post in postList" :key="post.id" class="post-card" hover-class="post-card-hover" @tap="handlePostTap(post)">
              <view class="post-deco"></view>
              <view class="post-header">
                <image :src="post.avatar" class="post-avatar" mode="aspectFill" />
                <view class="post-author">
                  <text class="post-name">{{ post.author }}</text>
                  <text class="post-time"> {{ post.time }} · {{ post.source }} </text>
                </view>
                <view class="post-tag">
                  <text>{{ post.tag }}</text>
                </view>
              </view>
              <view class="post-title">
                <text>{{ post.title }}</text>
              </view>
              <view class="post-content">
                <text>{{ post.summary }}</text>
              </view>
              <view v-if="post.cover" class="post-cover">
                <image :src="post.cover" mode="aspectFill" />
              </view>
              <view class="post-footer">
                <view class="post-action">
                  <text class="action-icon">👍</text>
                  <text class="action-text">{{ post.like }}</text>
                </view>
                <view class="post-action">
                  <text class="action-icon">💬</text>
                  <text class="action-text">{{ post.comment }}</text>
                </view>
                <view class="post-action">
                  <text class="action-icon">🔁</text>
                  <text class="action-text">{{ post.share }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="load-more">
            <view v-if="loadingMore" class="load-more-spinner"></view>
            <text class="load-more-text">
              {{ loadingMore ? '内容加载中...' : hasMore ? '上拉加载更多' : '到底啦，没有更多内容' }}
            </text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useSystemStore } from '@/stores/system'

const systemInfo = uni.getSystemInfoSync()
const systemStore = useSystemStore()
const { statusBarHeight } = storeToRefs(systemStore)
const windowHeight = systemInfo.windowHeight || 800
const scrollViewHeight = ref(0)

// 获取header-wrapper 高度
const headerWrapperHeight = ref(0)
// 获取页脚高度
const footerHeight = ref(0)
onMounted(() => {
  const query = uni.createSelectorQuery().in(this)
  query.select('.header-wrapper').boundingClientRect()
  query.exec((res) => {
    headerWrapperHeight.value = res[0].height
  })
  query.select('.footer').boundingClientRect()
  query.exec((res) => {
    footerHeight.value = res[0].height
  })
  scrollViewHeight.value = windowHeight - footerHeight.value - 30
})

const tabList = ['关注', '推荐', '热榜', '头条精选', '策略研习', '量化']
const activeTab = ref('推荐')

const hotList = [
  {
    rank: 1,
    title: '重新思考低空经济：无人机对军工与消费板块的双重拉动',
    heat: '792',
    tag: '研报解读'
  },
  {
    rank: 2,
    title: '龙虎榜席位拆解：星辉证券主攻锂电材料龙头',
    heat: '540',
    tag: '席位追踪'
  },
  {
    rank: 3,
    title: '稀土价格骤升，永磁概念股能否迎来第二春？',
    heat: '531',
    tag: '行业热点'
  },
  {
    rank: 4,
    title: '一进二策略复盘：本周准星命中率 78%',
    heat: '468',
    tag: '实盘复盘'
  },
  {
    rank: 5,
    title: 'AI+券商：智能客服与投顾的落地节奏',
    heat: '432',
    tag: '智能投顾'
  }
]

const postList = ref([
  {
    id: 'p1',
    author: '程序员爱炒股',
    time: '2 小时前',
    source: '热榜精选',
    tag: '龙虎榜',
    title: 'Python 实战：一键追踪龙虎榜高频席位',
    summary: '分享一个基于 Python + 聚宽 API 的席位追踪脚本，支持导出近 30 日上榜记录，并自动标记连板个股。',
    like: '1.2k',
    comment: '346',
    share: '128',
    avatar: 'https://images.unsplash.com/photo-1545239351-1141bd82e8a6?auto=format&fit=crop&w=200&h=200',
    cover: 'https://images.unsplash.com/photo-1520607162513-77705c0f0d4a?auto=format&fit=crop&w=640&h=360'
  },
  {
    id: 'p2',
    author: '玉宇夕落',
    time: '3 小时前',
    source: '策略研习',
    tag: '量化',
    title: '深入理解多因子模型：从回测框架到风险控制',
    summary: '本篇拆解自建多因子模型的全过程，包括因子选择、标准化、IC 验证以及风控模块搭建，附带可复现的回测链接。',
    like: '956',
    comment: '215',
    share: '89',
    avatar: 'https://images.unsplash.com/photo-1524504388940-b1c1722653e1?auto=format&fit=crop&w=200&h=200'
  },
  {
    id: 'p3',
    author: '雪球锦鲤',
    time: '5 小时前',
    source: '指数观察',
    tag: 'ETF',
    title: '沪深 300 回调 2%，该如何做波段防守？',
    summary: '仓位控制建议与期权对冲思路，附上近半年主要 ETF 的波动率曲线，欢迎交流自己的策略组合。',
    like: '643',
    comment: '188',
    share: '76',
    avatar: 'https://images.unsplash.com/photo-1520813792240-56fc4a3765a7?auto=format&fit=crop&w=200&h=200',
    cover: 'https://images.unsplash.com/photo-1483478550801-ceba5fe50e8e?auto=format&fit=crop&w=640&h=360'
  }
])

const refresherTriggered = ref(false)
const loadingMore = ref(false)
const hasMore = ref(true)
const refreshCursor = ref(0)
const moreCursor = ref(0)

const refreshPool = [
  [
    {
      id: 'rp1',
      author: '日内量化助手',
      time: '刚刚',
      source: '盘前精选',
      tag: '策略',
      title: '早盘必读：指数情绪温度计升至 63%',
      summary: '复盘昨夜外围市场与期指基差，结合热力图给出今日高开低走和高开高走的两套仓位建议。',
      like: '512',
      comment: '114',
      share: '46',
      avatar: 'https://images.unsplash.com/photo-1544723795-3fb6469f5b39?auto=format&fit=crop&w=200&h=200'
    },
    {
      id: 'rp2',
      author: '风控小指南',
      time: '刚刚',
      source: '风控播报',
      tag: '风控',
      title: '龙虎榜追踪提示：关注游资集中度回落',
      summary: '榜单中高频席位的平均持仓周期下降至 1.6 天，短线资金兑现更快，建议提高止盈的灵活度。',
      like: '428',
      comment: '97',
      share: '35',
      avatar: 'https://images.unsplash.com/photo-1544723795-3fb1c2f9a9ac?auto=format&fit=crop&w=200&h=200'
    }
  ],
  [
    {
      id: 'rp3',
      author: '板块雷达',
      time: '1 分钟前',
      source: '热点跟踪',
      tag: '题材',
      title: '算力链再起：东数西算午后异动',
      summary: '节点服务器订单环比+18%，结合营业部龙虎榜数据推演，预计主升浪将延续至周内。',
      like: '633',
      comment: '152',
      share: '58',
      avatar: 'https://images.unsplash.com/photo-1457449940276-e8deed18bfff?auto=format&fit=crop&w=200&h=200',
      cover: 'https://images.unsplash.com/photo-1520607162513-77705c0f0d4a?auto=format&fit=crop&w=640&h=360'
    }
  ],
  [
    {
      id: 'rp4',
      author: '盘后情绪站',
      time: '3 分钟前',
      source: '情绪监控',
      tag: '情绪',
      title: '情绪指标回暖：高标股晋级成功率回升到 41%',
      summary: '今日高标晋级率环比+12%，叠加外资净流入 36 亿，短线情绪有望延续修复行情。',
      like: '412',
      comment: '103',
      share: '27',
      avatar: 'https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?auto=format&fit=crop&w=200&h=200'
    }
  ]
]

const morePool = [
  [
    {
      id: 'mp1',
      author: 'CTA 观测站',
      time: '6 小时前',
      source: '量化沙龙',
      tag: '期货',
      title: '黑色系 CTA 策略月度榜：铁矿贡献过半收益',
      summary: '统计 20 套 CTA 策略的最新收益，铁矿 + PTA 波动贡献本月 54% 的收益，附带回撤对比图表。',
      like: '512',
      comment: '134',
      share: '42',
      avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?auto=format&fit=crop&w=200&h=200'
    },
    {
      id: 'mp2',
      author: 'Alpha 交易圈',
      time: '7 小时前',
      source: '策略研习',
      tag: '因子',
      title: '多空信号择时：拥挤度指标预警超买',
      summary: '通过拥挤度和北向资金净流入构建择时组合，本周信号提示降低科技股总仓位 15%。',
      like: '377',
      comment: '102',
      share: '31',
      avatar: 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?auto=format&fit=crop&w=200&h=200',
      cover: 'https://images.unsplash.com/photo-1454165205744-3b78555e5572?auto=format&fit=crop&w=640&h=360'
    }
  ],
  [
    {
      id: 'mp3',
      author: 'ETF 导航员',
      time: '昨天',
      source: '指数观察',
      tag: 'ETF',
      title: '港股科技 ETF 连续 5 日回补折价',
      summary: '从溢价率、成交额和资金流入三角度分析，南向资金在关键点位连续加仓，短期波段机会显现。',
      like: '284',
      comment: '79',
      share: '26',
      avatar: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?auto=format&fit=crop&w=200&h=200'
    },
    {
      id: 'mp4',
      author: 'T0 交易手记',
      time: '昨天',
      source: '实盘复盘',
      tag: '交易',
      title: '一进二策略：次日低吸的风控边界',
      summary: '结合近 50 单交易数据给出低吸与追高的盈亏对比，并分享 T0 对冲的执行细节。',
      like: '318',
      comment: '88',
      share: '29',
      avatar: 'https://images.unsplash.com/photo-1521572267360-ee0c2909d518?auto=format&fit=crop&w=200&h=200'
    }
  ],
  [
    {
      id: 'mp5',
      author: '机构调研纪要',
      time: '2 天前',
      source: '机构追踪',
      tag: '调研',
      title: '新能源逆势调研潮：锂电上游迎来密集回访',
      summary: '统计上周 47 场机构调研，锂电材料企业接待数量位列前二，外资多聚焦成本下降节奏。',
      like: '246',
      comment: '65',
      share: '22',
      avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?auto=format&fit=crop&w=200&h=200',
      cover: 'https://images.unsplash.com/photo-1526401485004-46910ecc8e51?auto=format&fit=crop&w=640&h=360'
    },
    {
      id: 'mp6',
      author: '交易日志本',
      time: '3 天前',
      source: '实盘复盘',
      tag: '心得',
      title: '日内回转策略：如何用盘口分时确认转强点',
      summary: '结合复盘软件导出的盘口截图，拆解五分钟回转策略的入场、加仓与止损框架。',
      like: '298',
      comment: '91',
      share: '34',
      avatar: 'https://images.unsplash.com/photo-1527980965255-d3b416303d12?auto=format&fit=crop&w=200&h=200'
    }
  ]
]

const handleTabChange = (tab) => {
  activeTab.value = tab
}

const handleRefresh = () => {
  if (refresherTriggered.value) {
    return
  }
  refresherTriggered.value = true
  setTimeout(() => {
    const packageIndex = refreshCursor.value % refreshPool.length
    const appendList = refreshPool[packageIndex].map((item, idx) => ({
      ...item,
      id: `${item.id}-${Date.now()}-${idx}`
    }))
    postList.value = [...appendList, ...postList.value]
    refreshCursor.value++
    moreCursor.value = 0
    hasMore.value = true
    refresherTriggered.value = false
  }, 1200)
}

const handleScrollToLower = () => {
  console.log('触发上拉加载更多')
  loadMore()
}

const loadMore = () => {
  if (loadingMore.value || !hasMore.value) {
    console.log('加载被阻止:', { loadingMore: loadingMore.value, hasMore: hasMore.value })
    return
  }
  console.log('开始加载更多，当前 moreCursor:', moreCursor.value)
  loadingMore.value = true
  setTimeout(() => {
    const nextPackage = morePool[moreCursor.value]
    if (!nextPackage) {
      hasMore.value = false
      loadingMore.value = false
      console.log('没有更多数据了')
      return
    }
    const extraList = nextPackage.map((item, idx) => ({
      ...item,
      id: `${item.id}-${Date.now()}-${idx}`
    }))
    postList.value = [...postList.value, ...extraList]
    moreCursor.value++
    hasMore.value = Boolean(morePool[moreCursor.value])
    loadingMore.value = false
    console.log('加载完成，新的 moreCursor:', moreCursor.value, 'hasMore:', hasMore.value)
  }, 1200)
}

const handlePostTap = (post) => {
  const targetUrl = `/pages/community/article/index?postId=${encodeURIComponent(post.id)}`
  uni.navigateTo({
    url: targetUrl,
    fail: () => {
      uni.showToast({
        title: '页面打开失败',
        icon: 'none'
      })
    }
  })
}
</script>

<style lang="scss">
@import './index.scss';
</style>
